package com.io.convert;

import java.io.*;
import java.util.Arrays;

/**
 * 序列化
 *
 * @author jiangbang
 * @date 2016/6/3
 */
public class ObjectInputStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        write("D:/demo/2.txt");
        read("D:/demo/2.txt");
    }
    //反序列化
    public static void read(String destPath) throws IOException, ClassNotFoundException {
        //创建源
        File dest = new File(destPath);
        //选择流
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dest)));
        //操作读取的顺序与写出一致，必须存在才能读取
        //不一致，数据存在问题
        Object obj = ois.readObject();
        if(obj instanceof Employee){
            Employee employee = (Employee) obj;
            System.out.println(employee.getName());
            System.out.println(employee.getSalary());
        }
        obj = ois.readObject();
        int[] arr=(int[])obj;
        System.out.println(Arrays.toString(arr));
    }

    //序列化
    public static void write(String destPath) throws IOException {
        Employee employee = new Employee("jiangbang",100000);
        int[] num = {1,2,3,4,5};
        //创建源
        File dest = new File(destPath);
        //选择流
        ObjectOutputStream dos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
        //操作写出的顺序，为读取准备
        dos.writeObject(employee);
        dos.writeObject(num);
        dos.flush();
        dos.close();
    }
}
